import React, {
  Component,
  useState,
  useEffect,
  useRef,
} from "react";
import {
  ScrollView,
  TouchableOpacity,
  Modal,
  Text,
  TouchableWithoutFeedback,
  View,
  Image,
} from "react-native";
import ImagePicker from "react-native-image-crop-picker";
import ImageViewer from "react-native-image-zoom-viewer";
import Content from "../../components/content/content";
import TaskDetailsComponent from "../../components/task-details/task-details";
import styles from "./check-details-sheet";
import uploadImage from "../../asset/images/upload-image.png";
import * as api from "../../api";
import * as config from "../../config";

export default function CheckDetails(props) {
  const id = props.navigation.state.params.applicant_id;
  const [data, setData] = useState([]);
  const [submitUrl, setSubmitUrl] = useState([]);
  const [images, setImages] = useState([]);
  const [modal, setModal] = useState(false);
  const [previewImages, setPreviewImages] = useState([]);
  const [showDetails, setShowDetails] = useState(false);

  const getCheckDetails = () => {
    global.showLoading();
    api.getCheckDetails({
      id,
    }).then(res => {
      setData(res);
      setShowDetails(true);
      setSubmitUrl(res.submit_url.map(v => {
        return {
          url: v,
        };
      }));
    }).catch(rej => {
      global.showToast(rej);
    }).finally(() => {
      global.closeLoading();
    });
  };

  useEffect(() => {
    getCheckDetails();
  }, []);

  const uploadImageFunc = () => {
    ImagePicker.openPicker({
      multiple: true,
      compressImageQuality: 0.7
    }).then(i => {
      const _images = [...images, ...i.map(v => {
        const newObj = {};
        newObj.width = v.width;
        newObj.height = v.height;
        newObj.key = v.path;

        newObj.props = {
          source: {
            uri: "file://" + v.path
          }
        };

        newObj.resource = v;

        return newObj;
      })];

      if (_images.length > config.MAX_UPLOAD_IMAGE) {
        global.showToast(`最多上传${config.MAX_UPLOAD_IMAGE}张图片, 请重新选择`);
      } else {
        setImages(_images);
      }
    });
  };

  const [imageIndex, setImageIndex] = useState(0);
  const viewImage = (index, type) => {
    setPreviewImages(type === 2 ? images : submitUrl);
    setImageIndex(index);
    setModal(true);
  };

  const submitTask = async () => {
    if (images.length === 0) {
      global.showToast('截图不能为空');
      return;
    }

    global.showLoading();
    try {
      let urls = null;
      await api.uploadFile(images).then((response) => response.text())
        .then((responseData) => {
          const res = JSON.parse(responseData);
          if (res.code === 0) {
            urls = res.data.urls;
          }
        });
      await api.submitTask({
        submit_url: urls,
        applicant_id: id,
      });
      global.showToast('提交成功');
      props.navigation.goBack();
    } catch (e) {
      global.showToast(e);
    } finally {
      global.closeLoading();
    }
  }

  return (
    <Content>
      <ScrollView alwaysBounceVertical={false}>
        <View style={styles.text}>
          <Text style={styles.word}>我的完成</Text>
        </View>
        <View style={styles.finish}>
          <Text style={styles.title}>截图: </Text>
          {
            submitUrl.map((value,index)=>
            <TouchableWithoutFeedback key={index} onPress={()=>{viewImage(index,1)}}> 
              <Image style={[styles.images, (index < 3 || (index - 3) % 4 !== 0) && styles.imagesLeft, index >= 3 && styles.imagesTop]} source={{uri:value.url,width: 222, height: 95, cache:'force-cache'}} />
            </TouchableWithoutFeedback>  
          )}
        </View>
        <View style={styles.text}>
          <Text style={styles.word}>任务详情</Text>
        </View>
        {showDetails?<TaskDetailsComponent {...data} /> :null}
        <View style={styles.content} >
          <View style={styles.row}>
            <Text style={styles.title}>截图: </Text>
            <View style={styles.imageContent}> 
              <TouchableWithoutFeedback onPress={uploadImageFunc} style={styles.uploadImageButton}>
                <Image style={styles.uploadImage} source={uploadImage} />
              </TouchableWithoutFeedback>
              {
                images.map((i, c)=>
                <TouchableWithoutFeedback key={i.key} onPress={()=>{viewImage(c,2)}}>
                  <Image style={[styles.images, (c < 3 || (c - 3) % 4 !== 0) && styles.imagesLeft, c >= 3 && styles.imagesTop]} source={i.props.source}/>
                </TouchableWithoutFeedback>  
              )}
            </View>  
          </View>
        </View> 
        <TouchableOpacity style={styles.buttonContent} onPress={submitTask}>
            <Text style={styles.button}>重新提交</Text>
        </TouchableOpacity>
      </ScrollView>

      <Modal animationType = {"slide"} visible = {modal} >
        <ImageViewer imageUrls={previewImages}
          enableImageZoom={true} // 是否开启手势缩放
          saveToLocalByLongPress={true} //是否开启长按保存
          index={imageIndex} // 初始显示第几张
          // failImageSource={} // 加载失败图片
          // loadingRender={this.renderLoad}
          enableSwipeDown={false}
          menuContext={{ "saveToLocal": "保存图片", "cancel": "取消" }}
          onChange={(index) => { }} // 图片切换时触发
          onClick={() => { // 图片单击事件
            setModal(false);}} 
        /> 
      </Modal>
    </Content>
  )
}